// 邀请好友砍价页面逻辑 (优化后的代码)
Page({
	data: {
		userInfo: {
			avatar: '',
			nickName: ''
		},
		price: '', //单价
		quantity: '', //数量
		progress: '', //砍价进度
		reducedAmount: '', //已砍金额
		totalAmount: '', //总共需要砍
		pay_amount: '', //直接购买
    image_url: '', //产品图
    productId:'',
    productTitle:'',
		options: {},
		participantId: '', //砍价参与id
		countdown: {},
		timer: null,
		helperRankList: [
			{
                "nickName": "微信用户1",
                "avatar": "https://yt3.ggpht.com/yti/ANjgQV8NVKopWke4nqIYQlPC6t__I2FofHAP0Ct7vYbr_PA1wg=s88-c-k-c0x00ffffff-no-rj",
                "helpedPrice": "2.5",
                "helpTime":"2分钟前"
			},
			{
                "nickName": "微信用户1",
                "avatar": "https://yt3.ggpht.com/yti/ANjgQV8NVKopWke4nqIYQlPC6t__I2FofHAP0Ct7vYbr_PA1wg=s88-c-k-c0x00ffffff-no-rj",
                "helpedPrice": "2.5",
                "helpTime":"2分钟前"
            }
		]
	},

	myShoes: function () {
		wx.reLaunch({
			url: '/pages/home1/index',
		});
	},

	onLoad: function (options) {
		const userInfo = wx.getStorageSync('userInfo');
        const nickName = userInfo?.nickName || '匿名用户';
		const avatar = userInfo?.avatarUrl || 'https://7072-prod-3gjcorog35addaa7-1348173015.tcb.qcloud.la/bargain/avatar.png?sign=39b094e6f7c0e2a56937bfefe4cc7c6d&t=1742596606';
		console.log(">>>invited1.onload.param2",options);
		this.setData({
			options: options,
			participantId: options.participantId,
			userInfo: {
				nickName,
				avatar
			}
		});
	},

	onShow: function () {
		// 开启分享功能
		wx.showShareMenu({
			withShareTicket: true,
			menus: ['shareAppMessage', 'shareTimeline'], // 显示分享按钮
		});

		this.onGetDetailInfo(); // 加载页面数据
	},

	/**
	 * 分享
	 */
	onShareAppMessage: function (res) {
		console.log(res.from);
		if (res.from === 'button') {
			return {
				title: '快来帮忙砍一刀，一起享优惠呀',
				desc: '快来帮忙砍一刀，一起享优惠呀',
				imageUrl: '',
				path: `/pages/invited/index?participantId=${this.data.participantId}`,
				success: function (res) {
					// 分享成功的处理逻辑
				},
				fail: function (res) {
					// 分享失败的处理逻辑
				},
			};
		}
	},

	onGetDetailInfo: function () {
		wx.showLoading({
			title: '加载中',
		});
		this.getDetail();
	},

	// 获取砍价详情
	getDetail: function () {
		wx.showLoading({
			title: '加载中',
    });
    let getBargainDetailRequest = {
			participantId: this.data.participantId,
		}
		wx.cloud.callFunction({
			name: 'xiaoBangCommonFunction',
			data: {
				getBargainDetailRequest: getBargainDetailRequest,
			},
			success: (res) => {
        console.log(">>>获取砍价详情res",JSON.stringify(res));
				let promesison = parseFloat(res.result.data.totalAmount) - parseFloat(res.result.data.reducedAmount);
				let progress = 1 - promesison / parseFloat(res.result.data.totalAmount);
				let percentage = (progress * 100).toFixed(2) + '%';
				console.log('> timeLeft: ', res.result.data.timeLeft);

				this.setData({
          participantId: res.result.data.participantId,
          productId: res.result.data.productId,
          productTitle: res.result.data.productTitle,
					price: res.result.data.price,
					quantity: res.result.data.quantity,
					reducedAmount: res.result.data.reducedAmount,
					image_url: res.result.data.imageUrl,
					totalAmount: res.result.data.totalAmount,
					pay_amount: res.result.data.payAmount,
					progress: percentage,
					timeLeft: res.result.data.timeLeft,
					helperRankList: res.result.data.helperRankList,
				});
				this.startCountdown()
				wx.hideLoading();
			},
			fail: (err) => {
				console.error('[云函数] [getBarginInfo] 调用失败', err);
			},
		});
	},
	timer: null, // 将 timer 放在 this 上，而不是 data 中
	convertSeconds(seconds) {
		const hours = Math.floor(seconds / 3600);
		const minutes = Math.floor((seconds % 3600) / 60);
		const remainingSeconds = seconds % 60;
		return { hours, minutes, seconds: remainingSeconds };
	},
	startCountdown() {
		// 清除之前的定时器
		if (this.timer) {
			clearTimeout(this.timer);
		}

		// 每秒更新一次倒计时
		const tick = () => {
			let { timeLeft } = this.data;

			if (timeLeft <= 0) {
				clearTimeout(this.timer); // 倒计时结束，清除定时器
				this.setData({ timeLeft: 0, countdown: this.convertSeconds(0) }); // 重置为 0
				wx.showToast({ title: '倒计时结束', icon: 'none' });
				return;
			}

			timeLeft -= 1; // 每秒减少 1 秒
			this.setData({
				timeLeft,
				countdown: this.convertSeconds(timeLeft) // 更新倒计时显示
			});

			// 递归调用
			this.timer = setTimeout(tick, 1000); // 每 1000ms 更新一次
		};

		tick(); // 启动倒计时
	},
	// 直接购买
	helpBargain: function () {
		wx.showLoading({
      title: '加载中',
    });
    let that = this;
	let helpBargainRequest = {
		participantId: that.data.participantId,
		helperId: wx.getStorageSync('openId'),
	}
    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction',
      data: {
        helpBargainRequest: helpBargainRequest,
      },
      success: (res) => {
        wx.hideLoading();
        console.log("helpBargain.helpBargainRequest res",JSON.stringify(res));
        if (res.result.code === 200) {
          wx.showToast({
            title: '砍价成功',
            icon: 'success',
            duration: 2000,
          });

          setTimeout(() => {
            this.getDetail();
          }, 300);
        } else {
          wx.showToast({
            title: res.result.message,
            icon: 'none',
            duration: 2000,
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('[云函数] [helpBargin] 调用失败', err);
		Logger.error('helpBargain.helpBargainRequest fail', JSON.stringify(err));
      },
    });
	},
	onPullDownRefresh() {
		this.getDetail();
		wx.stopPullDownRefresh();
	}
});